package com.weather.util;

import java.io.Reader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

/**
 * @Description Xml 构建工具类
 *
 * @author 堆堆堆
 * @date 2018年5月31日 下午5:14:29
 */
public class XmlBuilder {

	/**
	 * @param <T>
	 * @Description 将 Xml 转为指定的 POJO
	 *
	 * @param clazz
	 * @param xmlStr
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xmlStrToObject(Class<?> clazz, String xmlStr) throws Exception {

		Reader reader = new StringReader(xmlStr);
		JAXBContext context = JAXBContext.newInstance(clazz);

		// Xml 转为对象的接口
		Unmarshaller unmarshaller = context.createUnmarshaller();
		Object xmlObject = unmarshaller.unmarshal(reader);

		if (null != reader)
			reader.close();

		return (T) xmlObject;
	}
}
